package com.cnbot.toolkit.log.zlog;

import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 *  @项目名：  ToolKitModel
 *  @包名：    com.cnbot.toolkit.log.zlog
 *  @文件名:   ZLogProxy
 *  @创建者:   ww
 *  @创建时间:  2019/12/16 17:31
 *  @描述：    日志打印代理类
 */
public class ZLogProxy {

	private static LogQueue mLogQueue;
	private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.CHINA);
	private StringBuilder mStringBuilder = new StringBuilder();
	private LogDispatchRunnable mLogDispatchRunnable;

	private ZLogProxy() {
		mLogQueue = new LogQueue();
	}

	private static class SingletonHolder {
		private static final ZLogProxy INSTANCE = new ZLogProxy();
	}

	public static ZLogProxy get() {
		return SingletonHolder.INSTANCE;
	}

	/**
	 * 日志打印初始化，设置根路径并启动数据读取线程
	 * 在Application中初始化
	 * @param strategy
	 */
	public void init(ILogFileStrategy strategy) {
		mLogDispatchRunnable = new LogDispatchRunnable(mLogQueue.getBlockingQueue(), strategy);
		LogThreadPools.getInstance().iOScheduledThreadPool.scheduleWithFixedDelay(mLogDispatchRunnable, 0, 10, TimeUnit.MILLISECONDS);

	}

	public void add(String tag, String text, int logType) {
		mLogQueue.add(new LogBean(buildMessage(tag, text), logType));
	}

	public void allowSave(boolean allowed) {
        mLogDispatchRunnable.allowSave(allowed);
	}

    public void release(){
        LogThreadPools.getInstance().releaseThreadPool();
        mLogQueue.getBlockingQueue().clear();
    }

	private String buildMessage(String TAG, String text) {
		try {
			mStringBuilder.setLength(0);
			mStringBuilder.append(simpleDateFormat.format(new Date()));
			mStringBuilder.append("/");
			mStringBuilder.append(TAG);
			mStringBuilder.append("--->");
			mStringBuilder.append(text);
			mStringBuilder.append("\n\n");
			return mStringBuilder.toString();
		} catch (Exception var3) {
			Log.e(TAG, "buildMessage: ", var3);
			return "";
		}
	}
}
